package bb.lanxing.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import com.umeng.analytics.MobclickAgent;

import java.io.IOException;
import java.util.HashMap;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.bluetooth.WheelLengthSetting;
import bb.lanxing.activity.sns.SNSActivity;
import bb.lanxing.activity.sns.SNSActivityKt;
import bb.lanxing.activity.sns.SNSPlatform;
import bb.lanxing.activity.sns.SnsProviders;
import bb.lanxing.activity.sns.SnsViewModel;
import bb.lanxing.common.config.UmengEventConst;
import bb.lanxing.databinding.ActivityDeviceSettingsBinding;
import bb.lanxing.manager.RemoteSharedPreference;
import bb.lanxing.manager.SPConstant;
import bb.lanxing.model.database.User;
import bb.lanxing.mvvm.base.BaseDBActivity;
import bb.lanxing.mvvm.base.viewmodel.ContextAction;
import bb.lanxing.mvvm.sportsetting.SportSettingViewModel;
import bb.lanxing.mvvm.sportsetting.UserSportSetting;
//import bb.lanxing.network.BiciHttpClient;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.util.ui.InputHelper;
import bb.lanxing.view.BiciAlertDialogBuilder;
import kotlinx.coroutines.DebugKt;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class DeviceSettingsActivity extends BaseDBActivity<ActivityDeviceSettingsBinding> {
    public static String EXTRA_CADENCE_SEGMENT = "extra_cadence_alert";
    public static String EXTRA_FTP_SEGMENT = "extra_ftp_segment";
    public static String EXTRA_HEARTRATE_ALERT = "extra_heartrate_alert";
    public static String EXTRA_HEARTRATE_SEGMENT = "extra_heartrate_segment";
    private TextView cadenceWheelView;
    private View mCadenceSectionLayout;
    private View mCadenceWheelLayout;
    private View mHeartrateSectionLayout;
    private View mPowerFTPLayout;
    private View mPowerHRLTLayout;
    private View mPowerSectionLayout;
    private TextView powerFTPView;
    private TextView powerHRLTView;
    //private RelativeLayout rl_speed_alert_setting;
    private UserSportSetting setting;
    private TextView snsConnectedView;
    private View snsLayout;
    SportSettingViewModel viewModel = new SportSettingViewModel(App.getContext());
    SnsViewModel snsViewModel = null;
    private int lthr = 0;

    public interface OnSettingResultCallback {
        void onResult(String str);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_device_settings;
    }

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_device_settings);
        bindView(getWindow().getDecorView());
        setupActionBar(true);
        SnsViewModel snsViewModel = (SnsViewModel) createViewModelFromScope(SNSActivityKt.VIEW_MODEL_SCOPE_SNS, SnsViewModel.class);
        this.snsViewModel = snsViewModel;
        snsViewModel.getSnsAccounts();
        snsViewModel.getActionLiveData().observe(this, contextAction -> ContextAction.handle(contextAction.getAction(), new ContextAction.ActionHandler() {
            @Override
            public void onFinish(String str) {
            }

            @Override
            public void onReFresh(String str) {
            }

            @Override
            public void onShowLoading(String str) {
                DeviceSettingsActivity.this.showLoadingDialog(R.string.loading, true);
            }

            @Override
            public void onHideLoading(String str) {
                DeviceSettingsActivity.this.dismissLoadingDialog();
            }
        }));
        this.snsViewModel.mSnsProviders.observe(this, snsProviders -> {
            if (snsProviders != null && snsProviders.getProviders() != null && snsProviders.isStravaConnected()) {
                DeviceSettingsActivity.this.runOnUiThread(() -> DeviceSettingsActivity.this.snsConnectedView.setVisibility(View.VISIBLE));
            } else {
                DeviceSettingsActivity.this.runOnUiThread(() -> DeviceSettingsActivity.this.snsConnectedView.setVisibility(View.GONE));
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        float f = RemoteSharedPreference.getInstance().getFloat(SPConstant.KEY_WHEEL_LENGTH, 2.171f);
        TextView textView = this.cadenceWheelView;
        textView.setText((int) (f * 1000.0f) + " mm");
        this.viewModel.getSportSetting(App.getContext().getUserId());
        this.snsViewModel.getSnsAccounts();
    }

    public void onSnsClick(View view) {
        SnsProviders value = this.snsViewModel.mSnsProviders.getValue();
        if (value != null && value.getProviders() != null && value.isStravaConnected()) {
            new AlertDialog.Builder(this.context).setMessage(R.string.message_upgrade_fw_disconnecting).setNegativeButton(R.string.confirm, (dialogInterface, i) -> {
                dialogInterface.dismiss();
                DeviceSettingsActivity.this.snsViewModel.disConnectStrava();
            }).setPositiveButton(R.string.cancel, (dialogInterface, i) -> dialogInterface.cancel()).create().show();
        } else {
            SNSActivity.Companion.start(this.context, SNSPlatform.STRAVA);
        }
    }

    public void onHeartrateSectionClick(View view) {
        MobclickAgent.onEventValue(this, UmengEventConst.MINE_INFO_HR_SECTION, null, 1);
        Intent intent = new Intent(this, HeartrateSectionSettingActivity.class);
        UserSportSetting userSportSetting = this.setting;
        if (userSportSetting != null) {
            if (userSportSetting.getSegmentHeart() != null) {
                intent.putExtra(EXTRA_HEARTRATE_SEGMENT, this.setting.getSegmentHeart());
            }
            if (this.setting.getHeartrateAlarm() != null) {
                intent.putExtra(EXTRA_HEARTRATE_ALERT, this.setting.getHeartrateAlarm());
            }
        }
        startActivity(intent);
    }

    public void onCadenceSectionClick(View view) {
        MobclickAgent.onEventValue(this, UmengEventConst.MINE_INFO_CA_SECTION, null, 1);
        Intent intent = new Intent(this, CadenceSectionSettingActivity.class);
        UserSportSetting userSportSetting = this.setting;
        if (userSportSetting != null && userSportSetting.getSegmentCadence() != null) {
            intent.putExtra(EXTRA_CADENCE_SEGMENT, this.setting.getSegmentCadence());
        }
        startActivity(intent);
    }

    public void onPowerSectionClick(View view) {
        MobclickAgent.onEventValue(this, UmengEventConst.MINE_INFO_POWER_SECTION, null, 1);
        startActivity(new Intent(this, PowerSectionSettingActivity.class));
    }

    public void onCadenceWheelClick(View view) {
        MobclickAgent.onEventValue(this, UmengEventConst.MINE_INFO_WHEEL_PERIMETER, null, 1);
        showWheelSettingDialog();
    }

    public void onFTPClick(View view) {
        User signinUser = App.getContext().getSigninUser();
        showEditDialog(String.valueOf((signinUser == null || signinUser.getPowerFTP() <= 0.0f) ? 200.0f : signinUser.getPowerFTP()), str -> {
            float parseFloat = Float.parseFloat(str);
            User signinUser2 = App.getContext().getSigninUser();
            if (signinUser2 != null) {
                signinUser2.setPowerFTP(parseFloat);
                signinUser2.save();
            }
            DeviceSettingsActivity.this.powerFTPView.setText(String.valueOf(parseFloat));
            DeviceSettingsActivity.this.updateUserProfile("ftp", parseFloat);
        });
    }

    public void onHRLTClick(View view) {
        showEditDialog(String.valueOf(this.lthr), str -> {
            int parseFloat = (int) Float.parseFloat(str);
            User signinUser = App.getContext().getSigninUser();
            if (signinUser != null) {
                signinUser.setPowerHRLT(parseFloat);
                signinUser.save();
            }
            DeviceSettingsActivity.this.powerHRLTView.setText(String.valueOf(parseFloat));
            DeviceSettingsActivity.this.updateLTHR(parseFloat);
        });
    }

    private void showEditDialog(final String str, final OnSettingResultCallback onSettingResultCallback) {
        View inflate = LayoutInflater.from(this).inflate(R.layout.edittext_view, null);
        final EditText editText = inflate.findViewById(R.id.editText);
        editText.setInputType(4098);
        editText.setMaxLines(1);
        if (TextUtils.isEmpty(str)) {
            editText.setHint(R.string.dialog_hint_input);
        } else {
            editText.setText(str);
        }

        AlertDialog.Builder mo743setNegativeButton = new BiciAlertDialogBuilder(this).setView(inflate).setPositiveButton(R.string.dialog_btn_ok, (dialogInterface, i) -> {
            String trim = editText.getText().toString().trim();
            if (TextUtils.isEmpty(trim) || trim.equals(str)) {
                dialogInterface.cancel();
            } else {
                if (onSettingResultCallback != null) {
                    onSettingResultCallback.onResult(trim);
                }
            }
            InputHelper.hideSoftInput(editText);
        }).setNegativeButton(R.string.dialog_btn_cancel, (dialogInterface, i) -> InputHelper.hideSoftInput(editText));
        mo743setNegativeButton.setTitle(R.string.mine_device_setting_dialog_title);
        mo743setNegativeButton.show();
        InputHelper.showSoftInput(editText);
    }

    public void updateUserProfile(String str, Object obj) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put(str, obj);
        MyHttpClient.updateUserSetting(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException iOException) {
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
            }
        }, hashMap);
    }

    private void bindView(View view) {
        this.cadenceWheelView = view.findViewById(R.id.cadenceWheelView);
        this.powerFTPView = view.findViewById(R.id.powerFTPView);
        this.powerHRLTView = view.findViewById(R.id.powerHRLTView);
        this.mHeartrateSectionLayout = view.findViewById(R.id.heartrateSectionLayout);
        this.mCadenceSectionLayout = view.findViewById(R.id.cadenceSectionLayout);
        this.mPowerSectionLayout = view.findViewById(R.id.powerSectionLayout);
        this.mCadenceWheelLayout = view.findViewById(R.id.cadenceWheelLayout);
        this.mPowerFTPLayout = view.findViewById(R.id.powerFTPLayout);
        this.mPowerHRLTLayout = view.findViewById(R.id.powerHRLTLayout);
        //this.rl_speed_alert_setting = view.findViewById(R.id.rl_speed_alert_setting);
        this.snsLayout = view.findViewById(R.id.rl_sns_setting);
        this.snsConnectedView = view.findViewById(R.id.tv_status_connected);
        this.snsLayout.setOnClickListener(this::onSnsClick);
        this.mHeartrateSectionLayout.setOnClickListener(this::onHeartrateSectionClick);
        this.mCadenceSectionLayout.setOnClickListener(this::onCadenceSectionClick);
        this.mPowerSectionLayout.setOnClickListener(this::onPowerSectionClick);
        this.mCadenceWheelLayout.setOnClickListener(this::onCadenceWheelClick);
        this.mPowerFTPLayout.setOnClickListener(this::onFTPClick);
        this.mPowerHRLTLayout.setOnClickListener(this::onHRLTClick);

        //this.rl_speed_alert_setting.setOnClickListener(this::onSpeedAlertClick);
    }

    public void onSpeedAlertClick(View view) {
        startActivity(new Intent(this, SpeedAlertSettingActivity.class));
    }

    @Override
    public void initView(ActivityDeviceSettingsBinding activityDeviceSettingsBinding) {
        this.viewModel.getGetSettingResult().observe(this, userSportSetting -> {
            float powerHRLT = App.getContext().getSigninUser().getPowerHRLT();
            if (userSportSetting.getLthr() == null || userSportSetting.getLthr() == 0) {
                if (App.getContext().getSigninUser().getPowerHRLT() == 0.0f) {
                    return;
                }
                DeviceSettingsActivity.this.updateLTHR((int) powerHRLT);
                return;
            }
            DeviceSettingsActivity.this.lthr = userSportSetting.getLthr();
            TextView textView = powerHRLTView;
            textView.setText(lthr + "");
            setting = userSportSetting;
        });
        this.viewModel.getUpdateSettingResult().observe(this, userSportSetting -> {
            if (userSportSetting.getLthr() == null || userSportSetting.getLthr() == 0) {
                return;
            }
            lthr = userSportSetting.getLthr();
            powerHRLTView.setText(userSportSetting.getLthr().toString());
            setting = userSportSetting;
        });
    }

    private void showWheelSettingDialog() {
        new BiciAlertDialogBuilder(this)
                .setItems(new String[]{getString(R.string.mine_wheel_setting_dialog_item_custom), getString(R.string.mine_wheel_setting_dialog_item_check_table)}, (dialogInterface, i) -> {
            Intent intent = new Intent(DeviceSettingsActivity.this, WheelLengthSetting.class);
            intent.putExtra(DebugKt.DEBUG_PROPERTY_VALUE_AUTO, i != 0);
            startActivity(intent);
        }).show();
    }

    public void updateLTHR(int i) {
        this.viewModel.updateSportSetting(App.getContext().getUserId(), new UserSportSetting(null, null, i, null, null, null));
    }
}
